package com.bsbm.common.bean;

import org.richfaces.component.UITree;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.event.TreeToggleEvent;
import org.richfaces.model.TreeNodeImpl;

import javax.annotation.PostConstruct;
import javax.swing.tree.TreeNode;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ilya Shaikovsky
 *
 */
//@ManagedBean
//@ApplicationScoped
public class DynamicTreeBean extends TreeNodeImpl implements Serializable {
    //@ManagedProperty(value = "#{cdsParser.cdsList}")
    //private List<CDXmlDescriptor> cdXmlDescriptors;
    //private List<CDXmlDescriptor> cdXmlDescriptors = new CDParser().getCdsList();

    private List<TreeNode> rootNodes = new ArrayList<TreeNode>();
    private Map<String, Country> countriesCache = new HashMap<String, Country>();
    private Map<String, Company> companiesCache = new HashMap<String, Company>();
    private Map<String, List<CD>> companyCDsCache ;
    private TreeNode currentSelection = null;

    @PostConstruct
    public void init() {
        populateCountries();

/*        for (CDXmlDescriptor current : cdXmlDescriptors) {
            Country country = getCountryByName(current);
            Company company = getCompanyByName(current, country);
            CD cd = new CD(current.getTitle(), current.getArtist(), company, current.getPrice(), current.getYear());
            company.getCds().add(cd);
        }*/
    }

    private void populateCountries(){
        //Will be populated one time from database.
        Country usa = new Country();
        usa.setName("USA");
        List<Company> companies = new ArrayList<Company>();
        Company columbia = new Company();
        columbia.setName("columbia");
        columbia.setCountry(usa);
        Company rca = new Company();
        rca.setName("rca");
        rca.setCountry(usa);
        Company atlantic = new Company();
        atlantic.setName("atlantic");
        atlantic.setCountry(usa);
        Company grammy = new Company();
        grammy.setName("grammy");
        grammy.setCountry(usa);
        Company emi = new Company();
        emi.setName("emi");
        emi.setCountry(usa);
        companies.add(columbia);
        companies.add(rca);
        companies.add(atlantic);
        companies.add(grammy);
        companies.add(emi);
        usa.setCompanies(companies);
        rootNodes.add(usa);
    }

  /*  private Country getCountryByName(CDXmlDescriptor descriptor) {
        String countryName = descriptor.getCountry();
        Country country = countriesCache.get(countryName);
        if (country == null) {
            country = new Country();
            country.setName(countryName);
            countriesCache.put(countryName, country);
            rootNodes.add(country);
        }
        return country;
    }

    private Company getCompanyByName(CDXmlDescriptor descriptor, Country country) {
        String companyName = descriptor.getCompany();
        Company company = companiesCache.get(companyName);
        if (company == null) {
            company = new Company();
            company.setName(companyName);
            company.setParent(country);
            country.getCompanies().add(company);
            companiesCache.put(companyName, company);
        }
        return company;
    }   */

    public void processTreeToggle(TreeToggleEvent event){
        if(event.isExpanded()) {
            System.out.println("Inside processTreeToggle() for expanded event");
            UITree tree = (UITree) event.getSource();
            Object storedKey = tree.getRowKey();
            TreeNode selectedNode = (TreeNode) tree.getRowData();
            if (selectedNode instanceof Country) {
                Country country = (Country) selectedNode;
                System.out.println("No of companies under " + country.getName() + " is : " + country.getCompanies().size());
            } else if (selectedNode instanceof Company) {
                Company company = (Company) selectedNode;
                System.out.println("Before No of CDs under " + company.getName() + " is : " + company.getCds().size());
                company.setCds(getCdsByCompany(company));
                System.out.println("After No of CDs under " + company.getName() + " is : " + company.getCds().size());
            }


            //UITreeNode node = (UITreeNode)event.getSource();
            //UITree tree1 = (UITree)node.getParent();
            // FileSystemNode selectedNode = tree1.getRowData();
            /*Iterator<Object> keys = selectedNode.getChildrenKeysIterator();
            for (FileSystemNode child : selectedNode.getDirectories()) {
                selectedNode.addChild(child.getFile().hashCode(), child);
            }  */
        }else {
            System.out.print("Inside processTreeToggle() for collapsed event");
        }
    }

    private List<CD> getCdsByCompany(Company company) {
        if(companyCDsCache == null || companyCDsCache.keySet().size() == 0) {
            populateCompanyCDsCache();
        }
        List<CD> cds = companyCDsCache.get(company.getName());
        if(cds != null){
           for(CD cd : cds){
                  cd.setCompany(company);
            }
            return cds;
        }
        return new ArrayList<CD>();
    }
    private void populateCompanyCDsCache(){
        List<CD> cds1 = new ArrayList<CD>();
        CD cd1 = new CD("Hide your heart","Bonnie Tylor", 9.90f, 1890);
        CD cd2 = new CD("Empire Burlesque","Bob Dylan", 10.90f, 1895);
        CD cd3 = new CD("Greatest Hits","Dolly Parton", 8.30f, 1896);
        CD cd4 = new CD("Still got the blues","Gary More", 1.50f, 1898);
        CD cd5 = new CD("Eros","Eros Ramazzotti",2.60f, 1892);
        CD cd6 = new CD("One night only","Bee Gees", 79.50f, 1895);
        CD cd7 = new CD("Sylvias Mother","Dr.Hook", 89.60f, 1867);
        CD cd8 = new CD("Maggie May","Rod Stewart", 89.30f, 1878);
        CD cd9 = new CD("Romanza","Andrea Bocelli", 59.20f, 1895);
        CD cd10 = new CD("When a man loves a woman","Percy Sledge", 90.20f, 1900);
        CD cd11 = new CD("Black angel","Savage Rose", 8.80f, 1990);
        CD cd12 = new CD("1999 Grammy Nominees","Many", 7.70f, 1999);
        CD cd13 = new CD("For the good times","Kenny Rogers", 6.60f, 2000);
        CD cd14 = new CD("Big Willie style","Will Smith", 19.50f, 2001);
        cds1.add(cd1);
        cds1.add(cd2);
        cds1.add(cd3);
        List<CD> cds2 = new ArrayList<CD>();
        cds2.add(cd4);
        cds2.add(cd5);
        cds2.add(cd6);
        cds2.add(cd7);
        List<CD> cds3 = new ArrayList<CD>();
        cds3.add(cd6);
        cds3.add(cd6);
        cds3.add(cd8);
        cds3.add(cd9);
        cds3.add(cd10);
        List<CD> cds4 = new ArrayList<CD>();
        cds4.add(cd11);
        cds4.add(cd12);
        List<CD> cds5 = new ArrayList<CD>();
        cds5.add(cd13);
        cds5.add(cd14);
        companyCDsCache = new HashMap<String, List<CD>>();
        companyCDsCache.put("columbia",cds1);
        companyCDsCache.put("rca",cds2);
        companyCDsCache.put("atlantic",cds3);
        companyCDsCache.put("grammy",cds4);
        companyCDsCache.put("emi",cds5);
    }

    public void selectionChanged(TreeSelectionChangeEvent selectionChangeEvent) {
        // considering only single selection
        List<Object> selection = new ArrayList<Object>(selectionChangeEvent.getNewSelection());
        Object currentSelectionKey = selection.get(0);
        UITree tree = (UITree) selectionChangeEvent.getSource();

        Object storedKey = tree.getRowKey();
        tree.setRowKey(currentSelectionKey);
        currentSelection = (TreeNode) tree.getRowData();
        tree.setRowKey(storedKey);
    }

    public List<TreeNode> getRootNodes() {
        return rootNodes;
    }

    public void setRootNodes(List<TreeNode> rootNodes) {
        this.rootNodes = rootNodes;
    }

    public TreeNode getCurrentSelection() {
        return currentSelection;
    }

    public void setCurrentSelection(TreeNode currentSelection) {
        this.currentSelection = currentSelection;
    }

}